package com.ddlx.test.binder.util;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;

public class UpdateTextViewHander{

	private WeakReference<Activity> activityReference;
	private WeakReference<TextView> textViewReference;
	private Handler handler;
	public UpdateTextViewHander( Activity activity, TextView view ) {
		activityReference = new WeakReference<Activity>(activity);
		textViewReference = new WeakReference<TextView>(view);
		handler = new Handler( Looper.getMainLooper());
	}
	
	private TextView getTextView() {
		Activity activity = activityReference.get();
		if ( activity == null ) {
			return null;
		}
		TextView textView = textViewReference.get();
		if ( textView == null ) {
			return null;
		}
		return textView;
	}
	
	public void setText( final String string ) {
		handler.post( new Runnable() {
			
			@Override
			public void run() {
				TextView textView = getTextView();
				if ( textView != null ) {
					textView.setText(string+"\n");
				}
			}
		});
	}
	
	public void appendTextln( final String string ) {
		handler.post( new Runnable() {
			@Override
			public void run() {
				TextView textView = getTextView();
				if ( textView != null ) {
					textView.setText(textView.getText()+string+"\n");
				}
			}
		});
	}
	
	public void clear() {
		handler.post( new Runnable() {
					@Override
					public void run() {
						TextView textView = getTextView();
						if ( textView != null ) {
							textView.setText("");
						}
					}
				});
	}
}
